<?php
/**
 * 后台主函数库
 *
 * @author chenhao 2010-01-11
 * @copyright 呜雷科技(http://www.22cn.cn/) id: function.php
 */
function admin_showerr( $_backname, $_backurl, $_backid)
{
				if ( $_backid== 0 )
				{
								$_backcontent= "操作失败";
								$_backpic= "<font style=\"font-size:30px; color: red;\">×</font>";
				}
				else
				{
								$_backcontent= "操作成功";
								$_backpic= "<font style=\"font-size:30px; color: green;\">√</font>";
				}
				echo "<table width=\"70%\" border=\"1\" align=\"center\" cellpadding=\"5\" cellspacing=\"0\" class=\"table\"><tr>";
				echo "<td colspan=\"2\"><strong>".$_backcontent."</strong></td>";
				echo "</tr><tr>";
				echo "<td width=\"25%\" height=\"100px\" align=center><strong>".$_backpic."</strong></td>";
				echo "<td width=\"75%\">".$_backname."<li><a href={$_backurl}>返回上一级</a></li></td>";
				echo "</tr></table><br />";
				exit( );
}
function admin_showerrs( $_backname, $_backurl=null, $_backid)
{
				if ( $_backid== 0 )
				{
								$_backcontent= "操作失败";
								$_backpic= "<font style=\"font-size:30px; color: red;\">×</font>";
				}
				else
				{
								$_backcontent= "操作成功";
								$_backpic= "<font style=\"font-size:30px; color: green;\">√</font>";
				}
				if ( empty( $_backurl) )
				{
								$_backurl= "javascript:history.back(1)";
				}
				echo "<table width=\"70%\" border=\"1\" align=\"center\" cellpadding=\"5\" cellspacing=\"0\" class=\"table\"><tr>";
				echo "<td colspan=\"2\"><strong>".$_backcontent."</strong></td>";
				echo "</tr><tr>";
				echo "<td width=\"25%\" height=\"100px\" align=center><strong>".$_backpic."</strong></td>";
				echo "<td width=\"75%\">".$_backname."</td>";
				echo "</tr></table><br />";
				echo "<meta http-equiv=refresh content=2;url=".$_backurl.">";
				exit( );
}
function backdatebase( )
{
    global $DB_Database;
    $DB_Database_Content= "#Powered by CHPHP CMS 1.0 &copy; 2006-2009 028gc.com\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n\r\n/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\r\n/*!40103 SET TIME_ZONE='SYSTEM' */;\r\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE */;\r\n/*!40101 SET SQL_MODE='' */;\r\n/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES */;\r\n/*!40103 SET SQL_NOTES='ON' */;\r\n\r\nset charset utf8;\r\n".( "DROP DATABASE IF EXISTS `".$DB_Database."`;\r\n" ).( "CREATE DATABASE `".$DB_Database."`;\r\n" ).( "USE `".$DB_Database."`;\r\n" );
    $DB_Database_tables= mysql_query( "show tables" );
    while ( $DB_Database_a= mysql_fetch_array( $DB_Database_tables) )
    {
        $DB_Database_b= $DB_Database_a[0];
        $DB_Database_c= mysql_query("show create table`".$DB_Database_b."`");
        $DB_Database_d= mysql_fetch_array($DB_Database_c);
        $DB_Database_Content.= "#\r\n".("#Dumping data for table `".$DB_Database_b."`")."\r\n#\n\r\n\r\n";
        //$DB_Database_Content.= str_replace(chr(10),'',str_replace(chr(10).chr(32).chr(32), "", $DB_Database_d['Create Table'])).";\r\n\r\n/*!40101 SET NAMES utf8 */;\r\n";
        $DB_Database_Content.= $DB_Database_d['Create Table'].";\r\n\r\n/*!40101 SET NAMES utf8 */;\r\n";
        $DB_Database_q= mysql_query("select * from`".$DB_Database_b."`");
        while ( $DB_Database_f= mysql_fetch_assoc($DB_Database_q) )
        {
            $DB_Database_k= array_keys( $DB_Database_f);
            $DB_Database_k= array_map( "addslashes", $DB_Database_k);
            $DB_Database_k= join( "`,`", $DB_Database_k);
            $DB_Database_k= "`".$DB_Database_k."`";
            $DB_Database_v= array_values( $DB_Database_f);
            $DB_Database_v= array_map( "addslashes", $DB_Database_v);
            $DB_Database_v= join( "','", $DB_Database_v);
            $DB_Database_v= "'".$DB_Database_v."'";
            $DB_Database_Content.= "insert into `".$DB_Database_b."`({$DB_Database_k}) values({$DB_Database_v});\r\n";
        }
    }
    $DB_Database_Content.= "\r\n\r\n/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\r\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\r\n/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\r\n";
    if ( function_exists( "date_default_timezone_set" ) )
    {
        date_default_timezone_set( "Hongkong" );
    }
    $DB_Database_file= "dbback/".date( "Ymd_H_i_s" ).".sql";
    wfile( $DB_Database_file, $DB_Database_Content);
}

function GetNextSQL()
{
    global $fp;
    $DB_Database_d= "";
    while ( $DB_Database_get= @fgets( $fp, 40960 ) )
    {
        $DB_Database_get = trim($DB_Database_get);
        $DB_Database_get = str_replace( "\\\\", "\\", $DB_Database_get);
        $DB_Database_get = str_replace( "\\'", "''", $DB_Database_get);
        $DB_Database_get = str_replace( "\\r\\n", chr( 13 ).chr( 10 ), $DB_Database_get);
        $DB_Database_get = stripcslashes( $DB_Database_get);
        if ( 1 < strlen( $DB_Database_get) && $DB_Database_get[0] == "-" && $DB_Database_get[1] == "-" )
        {
            continue;
        }
        $DB_Database_d.= $DB_Database_get.chr( 13 ).chr( 10 );
        if ( !( 0 < strlen( $DB_Database_get) ) && !( $DB_Database_get[strlen( $DB_Database_get) - 1] == ";" ) )
        {
            continue;
        }
        break;
    }
    return $DB_Database_d;
}

function print_mysql_error( )
{
				echo "mysql_errno: ".mysql_errno( );
				echo "<br />";
				echo mysql_error( );
				@mysql_close( );
				exit( );
}

function addlog( $_logcontent, $_logname)
{
				global $db;
				if ( function_exists( "date_default_timezone_set" ) )
				{
								date_default_timezone_set( "Hongkong" );
				}
				@$_logtimeformat = @date( "Y-m-d H-i-s" );
				@$_obfuscate_NWGymn8 = @getenv( "SERVER_ADDR" );
				$db->query( "INSERT INTO tun2_log (logcontent,logtime,logoname,logip) VALUES \t\t('".$_logcontent."','{$_logtimeformat}','{$_logname}','".getip( )."')" );
}

function dafenglei_select($m,$id,$index)
{	
	global $class_arr;
	$n = str_pad('',$m,'-',STR_PAD_RIGHT);
	$n = str_replace("-","&nbsp;&nbsp;",$n);
	for($i=0;$i<count($class_arr);$i++){
	
		if($class_arr[$i][2]==$id){
			if($class_arr[$i][0]==$index){
				echo "        <option value=\"".$class_arr[$i][0]."\" selected=\"selected\">".$n."|--".$class_arr[$i][1]."</option>\n";
			}else{
				echo "        <option value=\"".$class_arr[$i][0]."\">".$n."|--".$class_arr[$i][1]."</option>\n";
			}
			dafenglei_select($m+1,$class_arr[$i][0],$index);
		}
	}
}
function work_back( $_workresults, $_workcontent='')
{
				if ( empty( $_workresults ) )
				{
								$_workresults = "操作成功！正在返回......";
				}
				if ( empty( $_workcontent) )
				{
								$_workcontent= "javascript:history.back(1)";
				}
				echo "<table width=\"70%\" border=\"1\" align=\"center\" cellpadding=\"5\" cellspacing=\"0\" class=\"table\"><tr height=\"100px\"><td>";
				echo "<CENTER> ".$_workresults." </CENTER>";
				echo "</td></tr></table><br />";
				if ( $_workcontent!= "exit" )
				{
								echo "<meta http-equiv=refresh content=2;url=".$_workcontent.">";
								exit( );
				}
				exit( );
}



function login_check( )
{
    if ( $_SESSION['admin'] != "ok" )
    {
        session_unset( );
        session_destroy( );
        header( "Location: Admin_Login.php" );
        exit( );
    }
}
/**
 * 栏目权限控制函数
 * @author chenhao 2010-01-11
 * @param int $_class_id 栏目ID
 * @param int $acl_id 权限级别
 * $_acl = array(0 => "添加内容",
				  1 => "修改内容",
	              //2 => "查看内容",
	              3 => "删除内容",
	              //4 => "添加顶级栏目",
	              5 => "添加子栏目",
	              6 => "编辑栏目",
	              7 => "删除栏目"
	            );
 * @return bool
 */
function acl_check($_class_id,$acl_id)
{
	if ($_SESSION['acl']==1) { //超级管理员不进行权限检查
		return true;
	} else {
		global $db1;
		$db1->query("SELECT acl_value FROM tun2_acl WHERE uid='$_SESSION[uid]' AND class_id='".$_class_id."'");
		if($db1->next_record())
		{
			$aclArray = explode(',',$db1->Record['acl_value']);
			return in_array($acl_id,$aclArray);
		}/* else {
			return false;
		}*/
	}
}
function echocolumns( $_columnstable, $_columnstr, $_columnstd)
{
				global $db1;
				$db1->query( "SELECT ".$_columnstr." FROM {$_columnstable} where id='{$_columnstd}'" );
				if ( $db1->next_record( ) )
				{
								echo $db1->Record[$_columnstr];
				}
}

function wfile( $_wfilea, $_wfileb, $_wfilec= "w" )
{
				$_wfiled = fopen( $_wfilea, $_wfilec);
				if ( !$_wfiled )
				{
								return false;
				}
				fwrite( $_wfiled, $_wfileb );
				fclose( $_wfiled );
				return true;
}

function getIP( )
{
				if ( getenv( "HTTP_CLIENT_IP" ) )
				{
								$_httpip = getenv( "HTTP_CLIENT_IP" );
								return $_httpip;
				}
				if ( getenv( "HTTP_X_FORWARDED_FOR" ) )
				{
								$_httpip = getenv( "HTTP_X_FORWARDED_FOR" );
								return $_httpip;
				}
				if ( getenv( "HTTP_X_FORWARDED" ) )
				{
								$_httpip = getenv( "HTTP_X_FORWARDED" );
								return $_httpip;
				}
				if ( getenv( "HTTP_FORWARDED_FOR" ) )
				{
								$_httpip = getenv( "HTTP_FORWARDED_FOR" );
								return $_httpip;
				}
				if ( getenv( "HTTP_FORWARDED" ) )
				{
								$_httpip = getenv( "HTTP_FORWARDED" );
								return $_httpip;
				}
				$_httpip = $_SERVER['REMOTE_ADDR'];
				return $_httpip;
}

function createFolder( $_createfoldername )
{
				if ( !file_exists( $_createfoldername ) )
				{
								createfolder( dirname( $_createfoldername ) );
								mkdir( $_createfoldername, 511 );
				}
}

function deldir( $_dirname)
{
				$_dirrun= opendir( $_dirname);
				while ( $_wfilea = readdir( $_dirrun) )
				{
								if ( !( $_wfilea != "." ) && !( $_wfilea != ".." ) )
								{
												$_dircontent= $_dirname."/".$_wfilea;
												if ( !is_dir( $_dircontent) )
												{
																unlink( $_dircontent);
												}
												else
												{
																deldir( $_dircontent);
												}
								}
				}
				closedir( $_dirrun);
				if ( rmdir( $_dirname) )
				{
								return true;
				}
				return false;
}

function delindexhtml( $_columnstd, $_indexname)
{
				global $db;
				$_indexsql= "SELECT webhtmlmode FROM tun2_config WHERE id =".$_columnstd;
				$db->query( $_indexsql);
				if ( $db->next_record() && $db->Record['webhtmlmode'] != $_indexname && $db->Record['webhtmlmode'] != "php" )
				{
								@unlink( "../index.".$db->Record['webhtmlmode'] );
				}
}

function toNum( $p )
{
				$p = trim( str_replace( ".", "", $p ) );
				if ( $p != "" )
				{
								return $p;
				}
}
function getClassPhone($classId) {
	global $db;
	$phoneArr = array();
	$sql = "SELECT phone FROM tun2_phone WHERE 1=1 ";
	if (isset($classId)) {
		$class = is_array($classId) ? implode(',',$classId) : $classId;
		$sql .= "AND class IN($class) ";
	}
	$sql .= "ORDER BY id DESC LIMIT 600"; //因每次最多只能发送600个手机号码
	$db->query($sql);
	while ($db->next_record()) {
		$phoneArr[] = $db->Record['phone'];
	}
	return $phoneArr;
}
//检测手机号码
function checkphone($phonearr){
	$match = '/^(13[0-9]|15[0|1|2|3|6|7|8|9]|18[8|9])\d{8}$/';
	if (is_array($phonearr)) {
		$new_phone = array();
		foreach ($phonearr as $key => $value) {
			if (preg_match($match,$value)) {
				$new_phone[] = $value;
			}
		}
		return $new_phone;
	}elseif (preg_match($match,$phonearr)) {
		return $phonearr;
	}else {
		return '';
	}
}

/**
 * 取得Excel表中的数据
 *
 * @param excel文件地址 $excel_file
 * @param 读取属性 $style
 * @return unknown
 */
function getExcelData($excel_file,$style='old') {
	require_once(WEB_ADMIN_PATH . 'module/excelimport/excelparser.php');
	$err_corr = "Unsupported format or file corrupted";
	
	if( $excel_file == '' ) fatal("No file uploaded");

	$exc = new ExcelFileParser("debug.log", ABC_NO_LOG);//ABC_NO_LOG ABC_VAR_DUMP);

	if( $style == 'old' )
	{
		$fh = @fopen ($excel_file,'rb');
		if( !$fh ) fatal("No file uploaded");
		if( filesize($excel_file)==0 ) fatal("No file uploaded");
		$fc = fread( $fh, filesize($excel_file) );
		@fclose($fh);
		if( strlen($fc) < filesize($excel_file) )
		fatal("Cannot read file");

		$time_start = getmicrotime();
		$res = $exc->ParseFromString($fc);
		$time_end = getmicrotime();
	}
	elseif( $style == 'segment' )
	{
		$time_start = getmicrotime();
		$res = $exc->ParseFromFile($excel_file);
		$time_end = getmicrotime();
	}

	switch ($res) {
		case 0: break;
		case 1: fatal("Can't open file");
		case 2: fatal("File too small to be an Excel file");
		case 3: fatal("Error reading file header");
		case 4: fatal("Error reading file");
		case 5: fatal("This is not an Excel file or file stored in Excel < 5.0");
		case 6: fatal("File corrupted");
		case 7: fatal("No Excel data found in file");
		case 8: fatal("Unsupported file version");

		default:
			fatal("Unknown error");
	}

	$getdata = array();
	for( $ws_num=0; $ws_num<count($exc->worksheet['name']); $ws_num++ )
	{
		$ws = $exc->worksheet['data'][$ws_num];
		if( is_array($ws) && isset($ws['max_row']) && isset($ws['max_col']) ) {
			for( $i=1; $i<=$ws['max_row']; $i++ ) {
				if(isset($ws['cell'][$i]) && is_array($ws['cell'][$i]) ) {
					for( $j=0; $j<=$ws['max_col']; $j++ ) {

						if( ( is_array($ws['cell'][$i]) ) && ( isset($ws['cell'][$i][$j]) )) {
							$data = $ws['cell'][$i][$j];

							switch ($data['type']) {
								case 0: // string
								$ind = $data['data'];
								if( $exc->sst['unicode'][$ind] ) {
									$s = uc2html($exc->sst['data'][$ind]);
								} else
								$s = $exc->sst['data'][$ind];
								if( strlen(trim($s))==0 )
								$s = '';
								else
								//print $s;
								$getdata[$i+1][] = $s;
								break;
								case 1: // integer number
								$getdata[$i+1][] = $data['data'];
								break;
								case 2: // float number
								$getdata[$i+1][] = $data['data'];
								break;
								case 3: // date
								$ret = $data[data];//str_replace ( " 00:00:00", "", gmdate("d-m-Y H:i:s",$exc->xls2tstamp($data[data])) );
								$getdata[$i+1][] = $ret;
								break;
								default:
									break;
							}
						} else {
							$getdata[$i+1][] = '';
						}
					}
				}
			}
		}
	}
	return $getdata;
}

//返回工作年限函数
function getWorkage($workageNum){
	$_workage = array(
	-1 => '在校学生',
	0  => '应届毕业生',
	1  => '1年以上',
	2  => '2年以上',
	3  => '3年以上',
	4  => '5年以上',
	5  => '8年以上',
	6  => '10年以上'
	);
	foreach($_workage as $key=>$value){
		if ($key==$workageNum) {
			return $value;
		}
	}
	return false;
}
//返回学历函数
function getSchoolRecord($recordNum){
	$_recordNum = array(
	0 => '中专以下',
	1 => '中专',
	2 => '高中',
	3 => '专科',
	4 => '本科',
	5 => '硕士',
	6 => '博士',
	7 => '博士以上'
	);
	foreach ($_recordNum as $key=>$value) {
		if ($recordNum==$key) {
			return $value;
		}
	}
	return false;
}
//取得用户申请职位（可能出现同一个用户申请多个职位的情况）
function getOffice($userID){
	global $db,$Conn;
	$sql = "SELECT b.title ".
	       "FROM tun2_office AS a ".
	       "LEFT JOIN tun2_content AS b ON a.office_id=b.id WHERE a.user_id=$userID";
	
	$result = mysql_query($sql,$Conn);
	$num = mysql_num_rows($result);
	if ($num>0) {//表示有记录
		while ($row=mysql_fetch_array($result)){
			if ($num>1) { //表示同一个用户申请了多个职位
				$str .= $row['title'].'&nbsp;&nbsp;';
			}else {
				$str = $row['title'];
			}
		}
		return $str;
	}
	return false;
}
//取得证件类型
function getCredentials($credentials){
	$_credentialsNum = array(
	0 => '身份证',
	1 => '军官证',
	2 => '护照',
	3 => '学生证'
	);
	foreach ($_credentialsNum as $key=>$value) {
		if ($credentials==$key) {
			return $value;
		}
	}
	return false;
}
//取得工作性质
function getNature($nature){
	$_nature = array(
	0 => '全职',
	1 => '兼职',
	2 => '临时'
	);
	foreach ($_nature as $key=>$value) {
		if ($nature==$key) {
			return $value;
		}
	}
	return false;
}
//取得第一外语水平
function getLanguage1Level($Language1Level){
	$_Language1Level = array(
	0 => '一般',
	1 => '熟练',
	2 => '精通'
	);
	foreach ($_Language1Level as $key=>$value) {
		if ($Language1Level==$key) {
			return $value;
		}
	}
	return false;
}
define( "COPY", "<font style=\"font-family:Arial, Helvetica, sans-serif; font-size:10px;\">Powered by 泸州北方化学工业有限公司 <strong>028gc.com cms 1.0 </strong>&copy; 2006-2009 <a href=\"http://www.028gc.com\" target=\"_blank\"><strong><font color=\"#ff3300\">028gc</font>.com</strong></a></font>" );
?>
